package com.ruoyi.web.controller.api;
import java.util.Date;

import com.github.pagehelper.PageHelper;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.RedisConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.xsp.domain.XspUser;
import com.ruoyi.xsp.domain.XspUserConcerned;
import com.ruoyi.xsp.domain.api.LoginUser;
import com.ruoyi.xsp.service.IXspUserConcernedService;
import com.ruoyi.xsp.service.IXspUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户管理 api
 * 
 * @author zhiminhu
 * @date 2021-01-22
 */
@Api(value = "用户信息管理",tags = "用户信息管理")
@RestController
@RequestMapping("/api/user")
public class XspUserApiController extends BaseApiController
{
    private static final Logger log = LoggerFactory.getLogger(XspUserApiController.class);

    @Autowired
    private IXspUserConcernedService xspUserConcernedService;

    /**
     * 登陆用户
     */
    @ApiOperation("登陆用户")
    @Log(title = "用户登陆", businessType = BusinessType.LOGIN)
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(HttpServletRequest request, LoginUser loginUser)
    {

        if(StringUtils.isBlank(loginUser.getSource())){
            return AjaxResult.error("来源不能为空");
        }
        return xspUserService.login(request,loginUser);
    }
    /**
     * 用户
     */
    @ApiOperation("获取用户信息ByUserCode")
    @GetMapping("/getUserInfoByUserCode")
    @ResponseBody
    public AjaxResult getUserInfoByUserCode(HttpServletRequest request,XspUser user)
    {
        if(user.getUserCode()<=0){
            return AjaxResult.error("userCode不能为空");
        }
        XspUser xspUser= redisCache.getCacheObject(RedisConstants.USER_INFO_PREFIX+user.getUserCode());
        if(xspUser==null) {
             xspUser = xspUserService.selectXspUserForCacheByUserCode(user.getUserCode());
        }
        String token = request.getHeader("TAP-CLIENT-TOKEN");
        XspUser xspUserCache=null;
        if (token != null) {
            //当我是登陆状态
            Long userCode= redisCache.getCacheObject(RedisConstants.TOKEN_USER_PREFIX+token);
            if(userCode==null || userCode<=0){
                return AjaxResult.error("登陆信息已经失效，请重新登陆！");
            }
            xspUserCache= redisCache.getCacheObject(RedisConstants.USER_INFO_PREFIX+userCode);
            if(xspUserCache==null) {
                //缓存失效 从新获取
                xspUserCache=xspUserService.selectXspUserForCacheByUserCode(Long.valueOf(userCode));
            }
            XspUserConcerned userConcerned=new XspUserConcerned();
            userConcerned.setFanUserCode(xspUserCache.getUserCode());
            userConcerned.setToUserCode(user.getUserCode());
            Long c= xspUserConcernedService.selectXspUserConcernedListCount(userConcerned);
            xspUser.setIConcernedIt(c>0);
        }
        if(xspUser==null) {
            return AjaxResult.error("userCode不存在");
        }
         return  AjaxResult.success(xspUser);
    }
    /**
     * 登陆用户
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    @ResponseBody
    public AjaxResult getUserInfo(HttpServletRequest request)
    {
        String token= request.getHeader("TAP-CLIENT-TOKEN");
        if (token == null) {
            return AjaxResult.error("登陆信息不能为空，请登录后在操作！");
        }
        Long userCode= redisCache.getCacheObject(RedisConstants.TOKEN_USER_PREFIX+token);
        if(userCode==null || userCode<=0){
            return AjaxResult.error("登陆信息已经失效，请重新登陆！");
        }
        XspUser xspUser= redisCache.getCacheObject(RedisConstants.USER_INFO_PREFIX+userCode);
        if(xspUser==null) {
            //缓存失效 从新获取
            xspUser=xspUserService.selectXspUserForCacheByUserCode(Long.valueOf(userCode));
        }
        return  AjaxResult.success(xspUser);
    }


    /**
     * 保存用户
     */
    @ApiOperation("修改用户信息")
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult editSave(HttpServletRequest request,XspUser xspUser)
    {
        String token= request.getHeader("TAP-CLIENT-TOKEN");
        if (token == null) {
            return AjaxResult.error("登陆信息不能为空，请登录后在操作！");
        }
        Long userCode= redisCache.getCacheObject(RedisConstants.TOKEN_USER_PREFIX+token);
        if(userCode==null || userCode<=0){
            return AjaxResult.error("登陆信息已经失效，请重新登陆！");
        }
        XspUser xspUserCache= redisCache.getCacheObject(RedisConstants.USER_INFO_PREFIX+userCode);
        if(xspUserCache==null) {
            //缓存失效 从新获取
            xspUserCache=xspUserService.selectXspUserForCacheByUserCode(Long.valueOf(userCode));
        }
        XspUser nowUser=new XspUser();
        nowUser.setUserId(xspUserCache.getUserId());
        nowUser.setLoginName(xspUser.getLoginName());
        nowUser.setNickname(xspUser.getNickname());
        nowUser.setRealName(xspUser.getRealName());
        nowUser.setEmail(xspUser.getEmail());
        nowUser.setBirthday(xspUser.getBirthday());
        nowUser.setSex(xspUser.getSex());
        nowUser.setAvatar(xspUser.getAvatar());
        nowUser.setIdiograph(xspUser.getIdiograph());
        nowUser.setProfile(xspUser.getProfile());
        nowUser.setLocation(xspUser.getLocation());
        nowUser.setCompany(xspUser.getCompany());
        nowUser.setBlog(xspUser.getBlog());
        nowUser.setWorker(xspUser.getWorker());
        nowUser.setToken(token);
        if(xspUserService.updateXspUser(nowUser)>0){
            xspUser= xspUserService.selectXspUserForCacheByUserCode(xspUser.getUserCode());
            return AjaxResult.success(xspUser);
        }else {
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 获取我的好友互相关注
     */
    @ApiOperation("我的好友")
    @GetMapping("/myFriend")
    @ResponseBody
    public AjaxResult myFriend(HttpServletRequest request)
    {
        String token= request.getHeader("TAP-CLIENT-TOKEN");
        if (token == null) {
            return AjaxResult.error("登陆信息不能为空，请登录后在操作！");
        }
        Long userCode= redisCache.getCacheObject(RedisConstants.TOKEN_USER_PREFIX+token);
        if(userCode==null || userCode<=0){
            return AjaxResult.error("登陆信息已经失效，请重新登陆！");
        }
        XspUser user=new XspUser();
        user.setUserCode(userCode);
        if(!StringUtils.isBlank(ServletUtils.getParameter(Constants.PAGE_SIZE_API))){
            startPage();
        }else{
            PageHelper.startPage(0, 10, "create_time desc");
        }
        List<XspUser> list = xspUserService.selectXspUserMyFriendList(user);
        return AjaxResult.success(getDataTable(list));
    }

    /***
     * 我的关注
     * @return
     */
    @ApiOperation("我的关注")
    @GetMapping("/myConcerned")
    @ResponseBody
    public AjaxResult myConcerned(HttpServletRequest request)
    {
        String token= request.getHeader("TAP-CLIENT-TOKEN");
        if (token == null) {
            return AjaxResult.error("登陆信息不能为空，请登录后在操作！");
        }
        Long userCode= redisCache.getCacheObject(RedisConstants.TOKEN_USER_PREFIX+token);
        if(userCode==null || userCode<=0){
            return AjaxResult.error("登陆信息已经失效，请重新登陆！");
        }
        XspUser user=new XspUser();
        user.setUserCode(userCode);
        startPage();
        List<XspUser> list = xspUserService.selectXspUserMyConcernedList(user);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 获取我的粉丝
     */
    @ApiOperation("我的粉丝")
    @GetMapping("/myFans")
    @ResponseBody
    public AjaxResult myFans(HttpServletRequest request)
    {
        String token= request.getHeader("TAP-CLIENT-TOKEN");
        if (token == null) {
            return AjaxResult.error("登陆信息不能为空，请登录后在操作！");
        }
        Long userCode= redisCache.getCacheObject(RedisConstants.TOKEN_USER_PREFIX+token);
        if(userCode==null || userCode<=0){
            return AjaxResult.error("登陆信息已经失效，请重新登陆！");
        }
        XspUser user=new XspUser();
        user.setUserCode(userCode);
        startPage();
        List<XspUser> list = xspUserService.selectXspUsermyFansList(user);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 查询用户管理列表
     */
    @PostMapping("/list")
    @ResponseBody
    public AjaxResult list(XspUser xspUser)
    {
        startPage();
        List<XspUser> list = xspUserService.selectXspUserList(xspUser);
        return AjaxResult.success(getDataTable(list));
    }
    /**
     * 关注好友
     */
    @ApiOperation("关注好友")
    @PostMapping("/friend")
    @ResponseBody
    public AjaxResult addFriend(HttpServletRequest request, @Param("userCode") Long ConcernedUserCode, @Param("type") Integer type) {
        if ( ConcernedUserCode==null || ConcernedUserCode == 0) {
            return AjaxResult.error("关注目标不能为空");
        }
        String token = request.getHeader("TAP-CLIENT-TOKEN");
        if (token == null) {
            return AjaxResult.error("登陆信息不能为空，请登录后在操作！");
        }
        Long userCode= redisCache.getCacheObject(RedisConstants.TOKEN_USER_PREFIX+token);
        if(userCode==null || userCode<=0){
            return AjaxResult.error("登陆信息已经失效，请重新登陆！");
        }
        XspUser xspUserCache= redisCache.getCacheObject(RedisConstants.USER_INFO_PREFIX+userCode);
        if(xspUserCache==null) {
            //缓存失效 从新获取
            xspUserCache=xspUserService.selectXspUserForCacheByUserCode(Long.valueOf(userCode));
        }
        XspUserConcerned userConcerned = new XspUserConcerned();
        userConcerned.setFanUserCode(xspUserCache.getUserCode());
        userConcerned.setToUserCode(ConcernedUserCode);

        List<XspUserConcerned> userConcerneds = xspUserConcernedService.selectXspUserConcernedList(userConcerned);

        if (type == null || type == 0) {
            if (userConcerneds == null || userConcerneds.size() == 0) {

                userConcerned.setToUserCode(ConcernedUserCode);
                userConcerned.setFanUserCode(xspUserCache.getUserCode());
                userConcerned.setIsFriend("");
                userConcerned.setCreateBy("");
                userConcerned.setCreateTime(new Date());
                userConcerned.setUpdateBy("");
                userConcerned.setUpdateTime(new Date());
                xspUserConcernedService.insertXspUserConcerned(userConcerned);
            } else {
                return AjaxResult.success("已经关注次好友");
            }

        } else {
            if (userConcerneds == null || userConcerneds.size() == 0) {
                return AjaxResult.success("没有关注此好友");
            } else {
                userConcerned = userConcerneds.get(0);
                xspUserConcernedService.deleteXspUserConcernedById(userConcerned.getId());
            }
        }
        return AjaxResult.success("操作成功");
    }


}
